package com.hnqcgczy.supplier.db;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务管理，调用时这么写。
 * MyTransaction transaction = new MyTransaction(false); // 开始事务，手动提交
 * try {
 * // 执行数据库操作
 * // ...
 * transaction.commit(); // 提交事务
 * } catch (Exception e) {
 * transaction.rollback(); // 回滚事务
 * e.printStackTrace();
 * } finally {
 * transaction.closeConn(); // 关闭数据库连接
 * }
 */
public class MyTransaction {
    private Connection connection;


    public MyTransaction(boolean isAutoCommit) {
        try {
            this.connection = new MyConnC3P0().getConnectionByMysql();
            //设置事务
            //true:自动提交事务
            //false:手动提交事务
            this.connection.setAutoCommit(isAutoCommit);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取设置了事务的数据库连接
     *
     * @return
     */
    public Connection getConn() {
        return connection;
    }

    /**
     * 关闭数据库
     */
    public void closeConn() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void commit() {
        try {
            connection.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void rollback() {
        try {
            connection.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
